<template>
  <div>
    <div class="xw-block" style="display: flex">
      <el-button type="primary" @click="add">新增角色</el-button>
      <el-popconfirm
          style="margin-left: 5px"
          confirm-button-text="确定"
          cancel-button-text="我再想想"
          icon="el-icon-info"
          icon-color="red"
          title="您确定要删除吗？"
          @confirm="delBatch"
      >
        <el-button slot="reference">批量删除</el-button>
      </el-popconfirm>
    </div>

    <el-table
        class="xw-block-table"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="角色名称"></el-table-column>
      <el-table-column prop="remark" label="角色描述" width="400" show-overflow-tooltip></el-table-column>
      <el-table-column
          label="操作"
          width="400">
        <template slot-scope="scope">
          <el-button size="small" :disabled="scope.row.name === 'ROLE_ADMIN'" @click="edit(scope.row)">编辑
          </el-button>
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="与之相关的用户角色将更新为默认角色，确认删除吗？"
              @confirm="confirmDel(scope.row.id)"
          >
            <el-button slot="reference" size="small" :disabled="scope.row.name === 'ROLE_ADMIN'">删除
            </el-button>
          </el-popconfirm>
          <el-button :disabled="scope.row.name === 'ROLE_ADMIN'" size="small" style="margin-left: 5px"
                     @click="allocationMenu(scope.row.id)">分配菜单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="xw-block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizeArr"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 新增/编辑角色抽屉 -->
    <MyDrawer ref="MyDrawer" :title="selectRow.id ? '更新角色' : '新增角色'" @saveOrUpdate="saveOrUpdate" @close="clearDrawer">
      <el-form :model="selectRow" :rules="rules" ref="roleForm" label-position="top">
        <el-form-item label="角色名称" prop="name">
          <el-input placeholder="请输入角色名称" v-model="selectRow.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input
              style="width: 85%"
              type="textarea"
              :rows="4"
              placeholder="请输入角色描述"
              v-model="selectRow.remark">
          </el-input>
        </el-form-item>
      </el-form>
    </MyDrawer>

    <MyDrawer ref="allocationMenu" size="25%" title="分配菜单" @saveOrUpdate="saveOrUpdateMenu">
      <el-tree
          ref="tree"
          :data="menuData"
          default-expand-all
          :default-checked-keys="checkedKeys"
          show-checkbox
          node-key="id"
          :props="defaultProps"
      >

      </el-tree>
    </MyDrawer>
  </div>
</template>
<script>
import MyDrawer from "@/components/MyDrawer.vue"

export default {
  data() {
    return {
      rules: { // 验证规则
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: "menuName"
      },
      menuData: [], // 所有的菜单
      checkedKeys: [], // 角色已经分配的不包含菜单目录的菜单ID
      selectRoleRow: {},
      delIds: [],
      selectRow: {},
      pageSizeArr: [10, 20, 30, 40],

      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        q: {}
      },
      total: 0,
      user: JSON.parse(localStorage.getItem("user"))
    }
  },
  components: {MyDrawer},
  mounted() {
    this.load()
  },
  methods: {
    // 分配菜单
    allocationMenu(roleId) {
      this.request.get("/role/selectRoleByMenu?roleId=" + roleId).then(res => {
        if (res.code === '200') {
          this.menuData = res.data.menus
          this.checkedKeys = res.data.checkedKeys
          this.selectRoleRow.roleId = roleId
          this.$refs.allocationMenu.open()
        }
      })
    },
    // 分配菜单的保存
    saveOrUpdateMenu() {
      // 获取选中的菜单
      let node = this.$refs.tree.getCheckedKeys()
      // 获取半选中的菜单
      let halfNode = this.$refs.tree.getHalfCheckedKeys()
      let roleMenuReq = [...node,...halfNode]
      if (!roleMenuReq || roleMenuReq.length == 0) {
        this.messageError("请选择菜单")
        return
      }
      this.selectRoleRow.menuIds = roleMenuReq
      this.request.post("/role/addRoleMenu",this.selectRoleRow).then(res => {
        if (res.code === '200') {
          this.messageSuccess("菜单分配成功")
          this.$refs.allocationMenu.close()
          this.load()
        } else {
          this.messageError(res.msg)
        }
      })
    },
    edit(row) {
      this.selectRow = { ...row };
      if (this.$refs.roleForm) {
        this.$refs.roleForm.resetFields();
      }
      this.$refs.MyDrawer.open();
    },
    add() {
      this.selectRow = {};
      if (this.$refs.roleForm) {
        this.$refs.roleForm.resetFields();
      }
      this.$refs.MyDrawer.open();
    },
    // 确认删除操作
    confirmDel(id) {
      this.request.delete("/role/" + id).then(res => {
        if (res.code === '200') {
          this.messageSuccess("角色删除成功，相关用户角色已更新为默认角色");
          this.load();
        } else {
          // 适配后端不太规范的数据格式，从data字段获取具体提示信息
          let errorMsg = res.data || res.msg;
          if (errorMsg === "默认角色不能删除，请重新选择要删除的角色") {
            this.messageError("默认角色不允许删除哦，请选择其他角色进行操作");
          } else if (errorMsg === "角色不存在") {
            this.messageError("要删除的角色不存在，请确认后再操作");
          } else {
            this.messageError("删除失败，原因：" + errorMsg);
          }
        }
      }).catch((error) => {
        // 捕获网络请求等其他异常情况并提示
        this.messageError("网络异常，删除操作未能正常执行，请稍后重试");
      });
    },
    delBatch() {
      if (this.delIds && this.delIds.length > 0) {
        this.request.post("/role/deleteBatchByIds", this.delIds).then(res => {
          if (res.code === '200') {
            this.messageSuccess("删除成功")
            this.load()
          } else {
            this.messageError("删除失败")
          }
        })
      } else {
        this.messageError("请先勾选数据")
      }
    },
    saveOrUpdate() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.request.post("/role/saveOrUpdate", this.selectRow).then(res => {
            if (res.code === '200') {
              this.messageSuccess("操作成功");
              this.$refs.MyDrawer.close();
              this.load();
            } else {
              this.messageError(res.msg);
            }
          });
        } else {
          this.messageError("请检查必填项是否填写完整");
        }
      });
    },
    load() {
      this.request.post("/role/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },
    handleSizeChange(size) {
      this.pageRequest.pageSize = size
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum
      this.load()
    },
    handleSelectionChange(e) {
      this.delIds = e.map(x => x.id)
    }
  }
}
</script>